﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dmutil.h"
#include "QFileDialog"
#include <QMessageBox>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    _Lua=new CIRT::cirt_lua;
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    std::string workpath= DMGetWorkPath();
    std::cout<< "workpath == "<<workpath<<std::endl;
    std::string exepath= DMGetExePath();
    std::cout<< "exepath == "<<exepath<<std::endl;

}


void MainWindow::on_pushButton_open_clicked()
{
    QString path=QFileDialog::getOpenFileName(this,"open lua",qApp->applicationDirPath()+"/../lua",tr("lua file(*.lua *.txt)"));
    //std::cout<<path.toStdString()<<std::endl;
    if(path.isEmpty())
        return;
    opendfile=path;
    ui->plainTextEdit->clear();
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return;
    }
    QString prostr=file.readAll();
    file.close();
    if(!prostr.isEmpty())
        ui->plainTextEdit->setPlainText(prostr);

}


void MainWindow::on_pushButton_save_clicked()
{
    if(opendfile.isEmpty())
    {
        on_pushButton_saveas_clicked();
        return;
    }

    QFile file(opendfile);
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        QMessageBox::warning(this,"Save Error","Save file failed,path = "+ opendfile);
        return;
    }
    QString pro= ui->plainTextEdit->toPlainText();
    if(pro.isEmpty())
    {
        QMessageBox::warning(this,"Save Error","current program is empty");
        file.close();
        return;
    }

    file.write(pro.toLatin1());
    QMessageBox::information(this,"save success","file saved successfuly!");
    file.close();

}


void MainWindow::on_pushButton_saveas_clicked()
{
    opendfile= QFileDialog::getSaveFileName(this,"save file","lua_file","lua file(*lua *.txt)");
    //std::cout<<opendfile.toStdString()<<std::endl;
    QFile file(opendfile);
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        QMessageBox::warning(this,"Save Error","Save file failed,path = "+ opendfile);
        return;
    }
    QString pro=ui->plainTextEdit->toPlainText();
    if(pro.isEmpty())
    {
        QMessageBox::warning(this,"Save Error","current program is empty");
        file.close();
        return;
    }
    file.write(pro.toLatin1());
    QMessageBox::information(this,"save success","file saved successfuly!");
    file.close();
}


void MainWindow::on_pushButton_run_clicked()
{
    QString pro=ui->plainTextEdit->toPlainText();
    std::cout<<"run programe ...."<<std::endl;
    _Lua->parserProgram(pro.toStdString());



}

